package com.linhngua.code.gwt.server;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;

import org.jboss.resteasy.plugins.providers.multipart.InputPart;
import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;
import org.jboss.resteasy.plugins.providers.multipart.MultipartInputImpl.PartImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.linhngua.code.data.shop.Item;
import com.linhngua.code.gwt.shared.FormFieldName;
import com.linhngua.code.hibernate.core.EntityManager;
import com.linhngua.code.hibernate.core.HibernateDataAccess;

@Path("/item")
public class ItemRS {
	
	private static final Logger					LOG	= LoggerFactory
															.getLogger(ItemRS.class);
	
	@Context
	ServletContext								servletContext;
	
	@Autowired
	@Qualifier("itemManager")
	EntityManager<Integer, Item> itemManager;
	
	@POST
	@Consumes(MediaType.MULTIPART_FORM_DATA)
	public Response receiveItem(MultipartFormDataInput parts)
			throws IOException, NumberFormatException {

		Item item = new Item();
		Map<String, List<InputPart>> map = parts.getFormDataMap();
		
		List<InputPart> list = map.get(FormFieldName.ITEM_NAME.name());
		if (list != null && list.size() > 0) {
			item.setName(list.get(0).getBodyAsString());
		}
		list = map.get(FormFieldName.ITEM_PRICE.name());
		if (list != null && list.size() > 0) {
			item.setPrice(Double.parseDouble(list.get(0).getBodyAsString()));
		}
		
		list = map.get(FormFieldName.ITEM_CURRENCY.name());
		if (list != null && list.size() > 0) {
			item.setCurrency(list.get(0).getBodyAsString());
		}
		
		list = map.get(FormFieldName.ITEM_ONSALE.name());
		if (list != null && list.size() > 0) {
			String onSaleText = list.get(0).getBodyAsString();
			boolean onSale = "on".equals(onSaleText);
			item.setOnSale(onSale);
			if (onSale) {
				list = map.get(FormFieldName.ITEM_DISCOUNT.name());
				if (list != null && list.size() > 0) {
					item.setDiscount(Double.parseDouble(list.get(0)
							.getBodyAsString()));
				}
			}
		}
		
		list = map.get(FormFieldName.ITEM_DESCRIPTION.name());
		if (list != null && list.size() > 0) {
			String description = list.get(0).getBodyAsString();
			item.setDescription(description);
			
		}
		receiveImage(FormFieldName.ITEM_IMAGE1.name(), map, item);
		receiveImage(FormFieldName.ITEM_IMAGE2.name(), map, item);
		receiveImage(FormFieldName.ITEM_IMAGE3.name(), map, item);
		item.setAddedDate(new Date());
		
		itemManager.save(item);
		
		return Response
				.created(
						UriBuilder.fromPath("ItemView.html?id=" + item.getId())
								.build()).build();
	}
	
	void receiveImage(String fieldName, Map<String, List<InputPart>> map,
			Item item) throws IOException {

		List<InputPart> list = map.get(fieldName);
		if (list != null && list.size() > 0) {
			PartImpl partImpl = (PartImpl) list.get(0);
			MediaType mediaType = partImpl.getMediaType();
			if (mediaType.getType().equals("image")) {
				String subType = mediaType.getSubtype();
				String imageName = new StringBuilder().append(item.getId())
						.append("/").append(fieldName).append(".")
						.append(subType).toString();
				String path = servletContext.getRealPath("images");
				
				// write image out
				BufferedImage image = ImageIO.read(partImpl.getBody());
				File imageFile = new File(path + "/" + imageName);
				imageFile.getParentFile().mkdirs();
				ImageIO.write(image, subType, imageFile);
				item.addImageUrls("images/" + imageName);
			}
		}
	}
}
